package com.bowen.demo.demo008.method2;

/**
 * <h3>java-study</h3>
 * <p>浅拷贝</p>
 * 在Java语言中，通过覆盖Object类的clone()方法可以实现浅克隆。
 *
 * 1. 被复制的类需要实现Clonenable接口（不实现的话在调用clone方法会抛出CloneNotSupportedException异常)， 该接口为标记接口(不含任何方法)
 * 2. 覆盖clone()方法，访问修饰符设为public。方法中调用super.clone()方法得到需要的复制对象。（native为本地方法)
 * @author : zhang.bw
 * @date : 2021-04-28 17:20
 **/
class Student implements Cloneable{
	private int number;

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	@Override
	public Object clone() {
		Student stu = null;
		try{
			stu = (Student)super.clone();
		}catch(CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return stu;
	}
}

class Test {

	public static void main(String args[]) {
		Student stu1 = new Student();
		stu1.setNumber(12345);
		Student stu2 = (Student)stu1.clone();

		System.out.println("学生1:" + stu1.getNumber());
		System.out.println("学生2:" + stu2.getNumber());

		stu2.setNumber(54321);

		System.out.println("学生1:" + stu1.getNumber());
		System.out.println("学生2:" + stu2.getNumber());
	}
}
